package com.alphathink.BitMapUtil;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

public class BitmapUtil {
	/**
	 * 根据数据加载图片。
	 * 
	 * @param url
	 * @param imageView
	 * @param targetWidth
	 *            可以为空。如果是null,将会根据imageview的大小确定
	 * @param targetHeight
	 *            可以为空。如果是null,将会根据imageview的大小确定
	 */
	public static void loadBitmap(String url, ImageView imageView,
			Integer targetWidth, Integer targetHeight) {
		if(null==url || "".equals(url)){
			return;
		}

		Bitmap bitmap = null;
		// ����Ƿ���memorycache.����򷵻�
		BitmapLruCache lruCache = BitmapLruCache.getInstance();
		bitmap = lruCache.get(url.hashCode() + "");
		if (bitmap != null) {
			System.out
					.println("BitmapLoadTask-->doInBackground-->MemoryCache hit!!---->pre!!");
			imageView.setImageBitmap(bitmap);
			return;
		}

		if (cancelPotentialWork(url, imageView)) {
			BitmapLoadTask loadTask = null;
			if (targetHeight != null && targetWidth != null) {
				loadTask = new BitmapLoadTask(url, imageView, targetWidth,
						targetHeight);
			} else {
				loadTask = new BitmapLoadTask(url, imageView);
			}
			AsyncDrawable asyncDrawable = new AsyncDrawable(loadTask);
			if (imageView != null) {
				imageView.setImageDrawable(asyncDrawable);
				loadTask.execute();
			}
		}
	}

	/**
	 * 根据加载数据和imageview判断是否需取消之前的任务，开启新的任务。
	 * 
	 * @param url
	 * @param imageview
	 * @return 返回true,表示需要启动新的任务。否则不需要启动新的任务任务。
	 */
	private static boolean cancelPotentialWork(String url, ImageView imageview) {
		final BitmapLoadTask loadTaks = getBitmapWorkerTask(imageview);
		if (loadTaks != null) {
			String bitmapData = loadTaks.getData();
			if (!url.equals(bitmapData)) {
				loadTaks.cancel(true);
			} else {
				return false;
			}
		}
		return true;
	}

	/**
	 * 一个辅助方法用来获取BitmapLoadTask.
	 * 
	 * @param imageView
	 * @return
	 */
	public static BitmapLoadTask getBitmapWorkerTask(ImageView imageView) {
		if (imageView != null) {
			final Drawable drawable = imageView.getDrawable();
			if (drawable instanceof AsyncDrawable) {
				AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
				return asyncDrawable.getBitmapWorkerTask();
			}
		}
		return null;
	}
}
